package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"ginfast/util"

	"github.com/gin-gonic/gin"
)

// Order 订单
type Order struct {
}

// ListHandler 列表
func (Order) ListHandler(c *gin.Context) {
	var data []model.Order
	err := orm.DbFind(&data)
	ginx.JSON(c).WriteData(data, err)
}

// PageHandler 分页
func (Order) PageHandler(c *gin.Context) {
	var p dto.Where
	ctx, err := ginx.MustBind(c, &p)
	if err != nil {
		return
	}
	var data []model.Order
	total, _ := p.DbModelWhere(&model.Order{}).Find(&data)
	ctx.WriteTotal(total, data)
}

// GetHandler 查询
func (Order) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Order{}, ginx.JSON(c))
}

// DeliverHandler 发货
func (Order) DeliverHandler(c *gin.Context) {
	ctx, idstr := ginx.MustParam(c, "id")
	if idstr == "" {
		return
	}
	ids := util.StringSplit(idstr, ",")
	err := orm.DbUpdateByID(&model.Order{}, ids, orm.H{"Status": 2})
	ctx.WriteError(err)
}

// DeleteHandler 关闭
func (Order) CloseHandler(c *gin.Context) {
	ctx, idstr := ginx.MustParam(c, "id")
	if idstr == "" {
		return
	}
	ids := util.StringSplit(idstr, ",")
	err := orm.DbUpdateByID(model.Order{}, ids, orm.H{"Status": 4})
	ctx.WriteError(err)
}

// AddHandler 新增
func (Order) AddHandler(c *gin.Context) {
	var p model.Order
	//获取参数
	ctx, err := ginx.MustBind(c, &p.OrderOpt)
	if err != nil {
		return
	}
	err = orm.DbCreate(&p)
	ctx.WriteError(err)
}

// UpdateHandler 修改
func (Order) UpdateHandler(c *gin.Context) {
	var p model.Order
	//获取参数
	ctx, err := ginx.MustBind(c, &p.OrderOpt)
	if err != nil {
		return
	}
	err = orm.DbUpdateModel(&p)
	ctx.WriteError(err)
}

// DeleteHandler 删除
func (Order) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Order{}, ginx.JSON(c))
}

func (o Order) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
}
